package com.zkh.myframe.database.mapper.parser;

import com.zkh.myframe.database.mapper.MapperParseException;
import com.zkh.myframe.database.mapper.tag.If;
import com.zkh.myframe.database.mapper.tag.Tag;
import com.zkh.myutils.markup.Element;
import com.zkh.myutils.utils.StringUtils;

/**
 * If解析器
 * @author zkh
 */
public class IfParser {
	
	/**
	 * 解析主方法
	 * @param node if标签节点
	 * @param namespace 命名空间
	 */
	public static If parse(Element node, String namespace) {
		//初始化
		If tif = new If();
		//ELSE标签
		Tag elseTag = new Tag();
		//当前是否是else标签
		boolean isElse = false;
		//获取条件
		String condition = node.getAttr("condition", true);
		//条件为空
		if(StringUtils.isEmpty(condition)) {
			throw new MapperParseException("condition条件不能为空");
		}
		tif.setCondition(condition);
		//当前标签
		Tag curr = tif;
		//没有子节点
		if(!node.hasChild()) {
			curr.appendSQL(node.getText(true).replaceAll("\\s+", " ").trim());
		}else {
			//遍历子节点
			for(Element cnode: node.getChildren()) {
				//标签名称
				String tagName = cnode.getName();
				//判断标签（include，trim，where，foreach，if或文本）
				if(cnode.isText()) {
					curr.appendSQL(cnode.getText(true).replaceAll("\\s+", " ").trim());
				}else if("include".equalsIgnoreCase(tagName)){
					curr.appendInclude(IncludeParser.parse(cnode, namespace));
					curr.appendSQL("{:include}");
				}else if("where".equalsIgnoreCase(tagName)) {
					curr.appendWhere(WhereParser.parse(cnode, namespace));
					curr.appendSQL("{:where}");
				}else if("foreach".equalsIgnoreCase(tagName)) {
					curr.appendForeach(ForeachParser.parse(cnode, namespace));
					curr.appendSQL("{:foreach}");
				}else if("if".equalsIgnoreCase(tagName)) {
					curr.appendIF(IfParser.parse(cnode, namespace));
					curr.appendSQL("{:if}");
				}else if("trim".equalsIgnoreCase(tagName)) {
					curr.appendTrim(TrimParser.parse(cnode, namespace));
					curr.appendSQL("{:trim}");
				}else if("elif".equalsIgnoreCase(tagName)) {
					//已经是else标签，则不再接收elif和else标签
					if(isElse) {
						throw new MapperParseException("else标签后面不能再使用elif标签");
					}
					//ELSEIF标签
					If elseIf = new If();
					//获取条件
					String subcondition = cnode.getAttr("condition", true);
					//条件为空
					if(StringUtils.isEmpty(subcondition)) {
						throw new MapperParseException("condition条件不能为空");
					}
					elseIf.setCondition(subcondition);
					//保存
					tif.appendElif(elseIf);
					//切换当前处理标签
					curr = elseIf;
				}else if("else".equals(tagName)) {
					//已经是ELse标签，则不再接收elif和else标签
					if(isElse) {
						throw new MapperParseException("else标签后面不能再使用else标签");
					}
					//保存ELSE标签
					tif.setElseTag(elseTag);
					//后面解析的均为elseTag
					curr = elseTag;
					//当前是else
					isElse = true;
				}
			}
		}
		//返回
		return tif;
	}
}
